﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Logging;
using NLog;
using Ubiquity.Core.Log.NLogger;
using ILogger = Microsoft.Extensions.Logging.ILogger;

namespace Ubiquity.Web.Filters
{
    public class ErrorResponse
    {

        public ErrorResponse(string msg)
        {
            Message = msg;
        }

        public string Message { get; set; }

        public object DeveloperMessage { get; set; }

    }
    public class ApplicationErrorResult : ObjectResult
    {
        public ApplicationErrorResult(object value) : base(value)
        {
            StatusCode = (int)HttpStatusCode.InternalServerError;
        }
    }
    /// <summary>
    /// 异常拦截器
    /// </summary>
    public class ErrorFilter : IExceptionFilter
    {
        //  readonly ILoggerFactory _loggerFactory;
      //  readonly IHostingEnvironment _env;
        //static readonly Logger Logger = LogManager.GetCurrentClassLogger();

        //public ErrorFilter(ILoggerFactory loggerFactory, IHostingEnvironment env)
        //{
        //    //   _loggerFactory = loggerFactory;
        //    _env = env;
        //}

        public void OnException(ExceptionContext context)
        {
            ILogger log = new NLogger("sd");
            log.LogDebug("LogDebug");
            log.LogInformation("LogInformation");
            log.LogWarning("d");
            log.LogTrace("Trace");
            // var logger = _loggerFactory.CreateLogger(context.Exception.TargetSite.ReflectedType);
            //log.Info("普通信息日志-----------");
            //log.Debug("调试日志-----------");

            //log.Warn("警告日志-----------");
            //log.Trace("跟踪日志-----------");
            //Logger.Log(NLog.LogLevel.Warn, "Log日志------------------");
            //Logger.Error("错误日志-----------");
            //Logger.Fatal("-----ss---");
            log.LogError(context.Exception,"");//全部异常信息

        
            var json = new ErrorResponse("未知错误,请重试");


            //if (_env.IsDevelopment())
            //    json.DeveloperMessage = context.Exception;


            context.Result = new ApplicationErrorResult(json);
            context.HttpContext.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
            context.ExceptionHandled = true;

        }

    }
}